import React from "react";
import BaseComponent from "../../redare/components/BaseComponent";
import {Empty, List, Modal, Result} from "antd";
import CommonPresenter from "../../.gen/presenter/CommonPresenter";
import ContainerComponent from "./ContainerComponent";
import ProjectDocFileInfoPresenter from "../../.gen/presenter/ProjectDocFileInfoPresenter";
import moment from "moment";
import SkeletonDivs from "./SkeletonDivs";

export default class FilePreviewModal extends BaseComponent {

    static defaultProps = {
        previewByVersion: true, //是否通过版本点击预览
        previewById: true,  //
    };

    constructor(props) {
        super(props);
        this.state = {
            isEmpty: true,
            loading: false,
            visible: false,
            versionData: undefined,
            current: undefined,
            convertFile: {},
            resultTitle: "",
        };
        this.commonPresenter = new CommonPresenter(this);
        this.docPresenter = new ProjectDocFileInfoPresenter(this);
    }

    //加载文档版本信息
    loadVersionData(id) {
        let {previewByVersion} = this.props;
        if (previewByVersion) {
            this.docPresenter.findProjectDocFileInfoList(
                {docFileId: id},
                {},
                (result) => {
                    let {data} = result;
                    this.setState({versionData: data});
                    if (data && data.length > 0) {
                        this.onVersionClick(data[0], 0)
                    }
                }
            )
        }
    }

    getConvertContent(record) {
        this.record = record;
        let {previewByVersion} = this.props;
        if (!previewByVersion) {
            this.props.previewById ? this.getFileHtmlById() : this.getFileContentByFile()
        } else {
            this.getFileContentByFile()
        }
    }

    //通过文件id查询预览
    getFileHtmlById() {
        this.commonPresenter.getFileHtml(
            {id: this.record},
            (result) => {
                let {data} = result;
                this.successCallback(data)
            },
            () => {
                this.failsCallback()
            }
        )
    }

    //通过文件信息查询预览
    getFileContentByFile() {
        this.commonPresenter.getFileContent(
            this.record,
            {},
            (result) => {
                let {data} = result;
                this.successCallback(data)
            },
            () => {
                this.failsCallback()
            }
        )
    }

    successCallback(data) {
        if (data.loadDone) {
            this.setState({convertFile: data});
            this.closeSpin()
        } else if (this.counter < 20) {
            setTimeout(() => {
                this.getConvertContent(this.record);
                this.counter += 1;
            }, 4000)
        } else {
            this.failsCallback()
        }
    }

    //渲染版本列表
    renderVersion() {
        let {versionData} = this.state;
        let node;
        if (!versionData) {
            node = <SkeletonDivs num={8}/>
        } else if (versionData.length > 0) {
            node = <List
                dataSource={this.state.versionData}
                renderItem={(item, index) => (
                    <List.Item
                        style={this.state.current === index ? {backgroundColor: "#d4d4d4", color: '#1890ff'} : null}
                        onClick={() => this.onVersionClick(item, index)}>
                        <div className={'item-content'}>
                            <div>版本{item.version}</div>
                            <div>{item.createTime ? moment(item.createTime).format('YYYY-MM-DD HH:mm:ss') : '-'}</div>
                        </div>
                    </List.Item>
                )}
            />
        } else {
            node = <Empty description="无文档版本信息" image={Empty.PRESENTED_IMAGE_SIMPLE}/>
        }
        return node
    }

    render() {
        return (
            <Modal
                title="文件预览"
                maskClosable={false}
                destroyOnClose={true}
                footer={null}
                visible={this.state.visible}
                onCancel={() => {
                    this.setModalVisible(false);
                    this.counter = 20;
                    this.clearState()
                }}
                width={"70%"}
                bodyStyle={{padding: 0, overflow: 'hidden'}}
            >
                <div className="preview-modal-foreign-div">
                    <ContainerComponent isRender={this.props.previewByVersion}>
                        <div className="preview-modal-first-div">
                            {this.renderVersion()}
                        </div>
                    </ContainerComponent>
                    <div className="preview-modal-last-div">
                        {this.renderSpin(
                            this.state.isEmpty ?
                                <Result status="warning" title={this.state.resultTitle}/> :
                                <div dangerouslySetInnerHTML={{__html: this.state.convertFile.content}}/>
                        )}
                    </div>
                </div>
            </Modal>
        );
    }

    //点击附件版本，加载预览
    onVersionClick(item, index) {
        this.setState({current: index, convertFile: {}, isEmpty: false});
        this.__showSpin();
        this.getConvertContent(item)
    }

    /**
     * 如果是通过版本预览，此时id为docFieldId
     * @param content 文件id  或者  文件信息（包含文件uri、type、size）  或者  docFileId
     * @private
     */
    __showModal(content) {
        this.counter = 0;
        if (Array.isArray(content)) {
            this.setState({versionData: content, resultTitle: "点击左侧版本进行预览"})
        }else {
            let {previewByVersion} = this.props;
            if (!previewByVersion) {
                this.__showSpin();
                this.setState({isEmpty: false});
                this.getConvertContent(content)
            } else {
                this.setState({resultTitle: "点击左侧版本进行预览"});
                this.loadVersionData(content)
            }
        }
        this.setModalVisible(true)
    }

    __showSpin() {
        this.showSpin("文档转换中...");
    }

    setModalVisible(visible) {
        this.setState({visible})
    }

    failsCallback() {
        this.setState({resultTitle: "文件预览失败", isEmpty: true});
        this.closeSpin()
    }

    //关闭时清除组件状态
    clearState() {
        this.setState({
            isEmpty: true,
            loading: false,
            visible: false,
            versionData: undefined,
            current: undefined,
            convertFile: {},
            resultTitle: ""
        })
    }

}